<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage as message } from 'element-plus'
import useUserList from './userList'
import useRoleList from '@/views/sysAuth/role/roleList'
import md5 from 'blueimp-md5'
import { PRIVATE_KEY } from '@/common/config'
import mySelect from '@/components/Select/mySelect.vue'
import { uploadFile } from '@/common/utils'

const props = defineProps<{
	editUser: { [key: string]: any }
}>()

type avatarFile = {
	uid: number | string
	name: string
	status: 'done' | 'uploading' | 'error'
	url: string
	[key: string]: any
}

interface userFormState {
	userName: string
	password: string
	nickName: string
	roleIds: string[]
	phone?: string
	avatarList: avatarFile[]
	[key: string]: any
}
const userState = reactive<userFormState>({
	userName: '',
	password: '',
	nickName: '',
	phone: '',
	roleIds: [],
	avatarList: [],
})
const formInstance = ref<FormInstance | null>(null)
const userList = useUserList()
const roleList = useRoleList()
const roleNameList = ref<{ label: string; value: string }[]>([])

const formLayout = {
	style: 'margin: 0 10px',
	labelWidth: 'auto',
	labelPosition: 'left',
}

const rules = {
	userName: [{ required: true, message: '请输入用户名！', trigger: 'change' }],
	password: [{ required: true, message: '请输入密码！', trigger: 'change' }],
	roleIds: [{ required: true, message: '请选择角色！', trigger: 'change' }],
	nickName: [{ required: true, message: '请输入昵称！', trigger: 'change' }],
}

function showBack() {
	Object.keys(userState).forEach((k) => {
		if (k != 'password' && k != 'roleIds' && k != 'avatarList') userState[k] = props.editUser[k]
		if (k == 'roleIds') userState.roleIds = props.editUser.roleIds.split(',')
		if (k == 'avatarList') {}
	})
}

function init() {
	formInstance.value?.resetFields()
	getRoleListName()
	showBack()
}

function getRoleListName() {
	roleNameList.value = roleList.list.map((v) => {
		return { label: v.roleName, value: v.id as string }
	})
}

function handleBeforeUpload(e: any) {
	if (userState.avatarList.length) {
		message.warning('只能上传一个头像，请先删除之前的！')
		return false
	}
}
function handleRemoveAvatar(e: any) {
	console.log(e, 'removebefore')
}
function handleUploadAvatar(e: any) {
	console.log(e, 'upload')
	// uploadFile(e.file)
}

async function formCommit() {
	try {
		await formInstance.value?.validate()

		let roleIds = '',
			roleNames = ''
		roleNameList.value.forEach((v) => {
			if (userState.roleIds.includes(v.value)) {
				if (!roleIds) roleIds = v.value
				else roleIds += ',' + v.value
				if (!roleNames) roleNames = v.label
				else roleNames += ',' + v.label
			}
		})
     
    const _userState:any=JSON.parse(JSON.stringify(userState))
		let params: userType
		if (!_userState.password) {
			delete _userState.password
			params = { ...props.editUser, ..._userState, roleIds, roleNames, id: props.editUser.id }
		} else params = { ...props.editUser, ..._userState, password: md5((_userState.password, PRIVATE_KEY)), roleIds, roleNames, id: props.editUser.id }
		delete params.avatarList
		const res = await userList.updateItem(params)
		if (res.code == 200) {
			return true
		} else if (res.code == 201) message.error('用户名已存在！')
	} catch (error) {
		console.log(error)
	}
}

defineExpose({
	init,
	formCommit,
})
</script>

<template>
	<el-form :model="userState" :rules="rules" v-bind="formLayout" ref="formInstance">
		<el-row :gutter="24">
			<el-col :span="12">
				<el-form-item prop="userName" label="用户名">
					<el-input v-model="userState.userName" placeholder="用户名必须唯一" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="password" label="密码">
					<el-input type="password" show-password v-model="userState.password" placeholder="请输入密码" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="nickName" label="昵称">
					<el-input v-model="userState.nickName" placeholder="请输入昵称" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="phone" label="手机号">
					<el-input v-model="userState.phone" placeholder="请输入手机号" allowClear />
				</el-form-item>
			</el-col>

			<el-col :span="24">
				<el-form-item prop="roleIds" label="拥有的角色">
					<mySelect style="width: 100%" multiple v-model="userState.roleIds" placeholder="请选择拥有的角色" clearable :select-options="(roleNameList as any)" />
				</el-form-item>
			</el-col>

			<el-col :span="24">
				<el-form-item prop="avatarList" label="头像">
					<el-upload
						accept=".png, .jpg, .jpeg"
						v-model:file-list="userState.avatarList"
						list-type="picture-card"
						:before-upload="handleBeforeUpload"
						:before-remove="handleRemoveAvatar"
						:http-request="handleUploadAvatar"
						drag
					>
						<div style="text-align: center">
							<el-icon><Plus /></el-icon>
							<div style="margin-top: 8px">点击或拖拽上传</div>
						</div>
					</el-upload>
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
</template>
